package com.pignest.hotel.module.global;

import org.apache.commons.lang.StringUtils;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

import com.pignest.hotel.beans.Dictionary;
import com.pignest.hotel.service.DictionaryService;
import com.pignest.hotel.spring.Services;
import com.pignest.hotel.system.L;

public class DictionaryWindow extends Window {
	private static final long serialVersionUID = 2147239767923279155L;
	
	private String dictionaryId;
	private Dictionary dictionary;
	private Textbox keyField;
	private Textbox valueField;
	
	private void init() {
		keyField = (Textbox)getFellow("keyField");
		valueField = (Textbox)getFellow("valueField");
	}

	private void setDictionary(Dictionary dict) {
		if (keyField == null)
			init();
		keyField.setValue(dict == null ? null : dict.getKey());
		valueField.setValue(dict == null ? null : dict.getValue());
	}
	
	public void reset() {
		setDictionaryId(null);
	}
	
	public boolean save() {
		if (keyField == null)
			init();
		String key = keyField.getValue();
		String value = valueField.getValue();
		if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) {
			return false;
		}
		DictionaryService service = Services.getDictionaryService();
		if (StringUtils.isEmpty(dictionaryId)) {
			Dictionary dict = new Dictionary();
			dict.setKey(key);
			dict.setValue(value);
			service.addDictionary(dict);
			L.insert(dict);
		} else {
			Dictionary dict = dictionary;
			if (key.equals(dict.getKey()) && value.equals(dict.getValue()))
				return true;
			if (service.exists(key, value))
				return false;
			dict.setKey(key);
			dict.setValue(value);
			service.updateDictionary(dict);
			L.update(dict);
		}
		return true;
	}
	
	public void setDictionaryId(String dictionaryId) {
		Dictionary dictionary = dictionaryId == null ? null : Services.getDictionaryService().getDictionary(dictionaryId);
		if (dictionary != null) {
			this.dictionaryId = dictionaryId;
			this.dictionary = dictionary;
		}
		setDictionary(dictionary);
	}
}
